<template>
<div class="detailed-population-density">
  <div id="detailed-population-density-main"></div>
</div>
</template>

<style scoped>
.detailed-population-density{
  width: 100%;
  height: 65vh;
}

#detailed-population-density-main{
  width: 75vw;
  height: 65vh;
}
</style>

<script setup>
import emitter from "@/utils/emitter.js";
import {detailedPopulationDensityEvent} from "@/consts/eventName.js";
import {onMounted} from "vue";
import {useDetailedStore} from "@/store/useDetailedStore.js";
import {getPopulationDensityByCity} from "@/api/population.js";
import * as echarts from "echarts";
import theme from "../../../static/theme/walden.json";

let detailedStore = useDetailedStore()
let chartDom
let myChart
let option;


onMounted(()=>{
  detailedStore.detailedLoadFlag.set(detailedPopulationDensityEvent,true)
  let cityName = detailedStore.detailedData.get(detailedPopulationDensityEvent)

  chartDom = document.getElementById('detailed-population-density-main');
  myChart = echarts.init(chartDom,theme);

  getData(cityName)

})

function getData(cityName){
  getPopulationDensityByCity(cityName).then((value)=>{
    let data = value.data
    let xData = []
    let sData = []

    data.forEach((item)=>{
      const jsonMap = new Map(Object.entries(item));

      xData.push(jsonMap.keys().next().value)
      sData.push(jsonMap.values().next().value)
    })
    return {
      xData:xData,
      sData:sData
    }
  }).then((value)=>{
    option = createOption(value,cityName)

    myChart.setOption(option);
  })
}

function createOption(value,city){
  return {
    title: {
      text: city+'-人口密度',
      left: "center"
    },
    legend:{
      right:10
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '1%',
      right: '1%',
      bottom: '1%',
      top: '23%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: value.xData.reverse()
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '人口密度（人/平方公里）',
        type: 'line',
        stack: 'Total',
        data: value.sData.reverse()
      },
    ]
  };
}

emitter.on(detailedPopulationDensityEvent,(value)=>{
  getData(value)
})
</script>
